<template>
  <div class="login_container" :style="backImgStyle">
    <el-row> <el-button type="info" round style=" margin-left:90%;" @click="toHome">返回主页</el-button></el-row>
    <div class="login_x">
      <div class="inner_box">
        <el-form ref="loginForm" :rules="loginRules" :model="loginForm" class="login-form" auto-complete="on"
                 label-position="left">
          <div class="title-container">
            <div class="login_header">
              <a @click="loginByPassword" :class="{active:cur==true}">账号密码登录</a>
              <a @click="loginByCode" :class="{active:cur==false}">手机快捷登录</a>
            </div>
          </div>
          <div class="login_content">
            <div v-if="cur==true" class="body_item">
              <el-form-item prop="phoneNumber">

                <el-input ref="phoneNumber" v-model="loginForm.phoneNumber" placeholder="请输入手机号"
                          name="phoneNumber"
                          type="text"
                          tabindex="1" auto-complete="on"/>
              </el-form-item>

              <el-form-item prop="password">

                <el-input :key="passwordType" ref="password" v-model="loginForm.password" :type="passwordType"
                          placeholder="请输入密码" name="password" tabindex="2" auto-complete="on"
                          @keyup.enter.native="login"/>

              </el-form-item>

              <br>
            </div>
            <div v-if="cur==false" class="body_item">
              <el-form-item prop="phoneNumber">

                <el-input ref="mobile" v-model="loginForm.phoneNumber" placeholder="请输入手机号" name="phoneNumber"
                          type="text"
                          tabindex="1" auto-complete="on"/>
              </el-form-item>
              <el-form-item prop="code">

                <el-input ref="code" v-model="loginForm.code" type="text" placeholder="请输入验证码" name="code"
                          abindex="2"
                          maxlength="6" auto-complete="on" @keyup.enter.native="login"/>
                <span class="show-pwd">
                  <el-button :loading="sending" :disabled="sendDisabled" size="small"
                             @click="onSendSms">{{ sendButtonText }}</el-button>
                </span>
              </el-form-item>
            </div>
          </div>
          <el-button :loading="loading" style="width:100%;margin-bottom:20px;color:#ffffff;background-color: #4e7ca1"
                     @click.native.prevent="login">登录
          </el-button>
          <a href="" @click.prevent="toRegister" style="margin-left: 40%">立即注册</a>
        </el-form>
      </div>
    </div>
  </div>

</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      backImgStyle: {
        backgroundImage: "https://eladmin.vip/demo/static/img/background.df9c4cdb.web"
      },
      loginForm: {
        phoneNumber: "",// 手机号
        code: "",// 验证码
        password: '', //密码
        checked: false,//记住密码
      },
      loginRules: {
        phoneNumber: [{required: true, message: "手机号不能为空！", trigger: "blur"},
          {pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur'},
          {min: 11, max: 11, message: "请输入11位的手机号！", trigger: 'blur'}],
        password: [{
          required: true,
          pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
          message: "不能为空，长度8-20位，必须包含英文大小写+数字",
          trigger: 'blur'
        }],
        code: [{required: true, message: "验证码不能为空！", trigger: "blur"}]
      },
      cur: true,//true代表密码, false代表短信
      sending: false,
      sendDisabled: false,
      loading: false,
      timer: 0,
      passwordType: 'password',


    };
  },
  computed: {
    sendButtonText() {
      if (this.timer === 0) {
        this.sending = false;
        return "发送验证码";
      } else {
        return `${this.timer}秒后重发`;
      }
    }
  },
  watch: {

    timer(num) {
      if (num > 0) {
        setTimeout(() => {
          this.timer = --num;
        }, 1000);
      }
    },

  },
  created() {

  },

  methods: {

    toHome(){
      sessionStorage.setItem("isShowMainBody",false)
      window.location.href= '/'

    },
    onSendSms() {

      this.loginWay = false;
      this.$refs.loginForm.validateField("phoneNumber", err => {
        if (!err) {
          this.$axios.postForm("/user/sendLoginCode", this.loginForm).then(response => {
            if (response.data.code == 200) {
              this.sending = true;
              const {phoneNumber} = this.loginForm;
              this.$message({
                message: "短信已发送成功，请注意查收",
                type: "success",
                duration: 2000,
              })
              this.timer = 60;

            } else {
              this.$message({
                message: "网络异常！请稍后再试",
                type: "error",
                duration: 2000,
              })
            }

          }).catch(reason => {
            this.$message({
              message: "网络异常！请稍后再试",
              type: "error",
              duration: 2000,
            })
          })
        }
      });
    },
    showPwd() {
      this.loginWay = true;
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    login() {
      this.$refs.loginForm.validate(isValid => {
        if (!isValid) {
          this.$message({
            message: "请正确填写",
            type: "error",
            duration: 2000,
          })
          return;
        } else {
          this.$axios.postForm("/user/login", this.loginForm).then(response => {
            if (response.data.code == 200) {
              this.$message({
                message: "登陆成功！",
                type: "success",
                duration: 2000,
              })
              sessionStorage.setItem("isShowMainBody",false)
              sessionStorage.setItem("role",response.data.data.role)
              sessionStorage.setItem("token", response.data.data.token);
              if (response.data.data.role == "9"||response.data.data.role=="11") this.$router.push("/BackgroundManage")
              else this.$router.push("/")
            } else {
              this.$message({
                message: response.data.data.msg,
                type: "error",
                duration: 2000,
              })
            }
          })
        }
      })
    },
    loginByPassword() {
      this.cur = true;
      this.refreshLoginForm();
    },
    loginByCode() {
      this.cur = false;
      this.refreshLoginForm();
    },
    refreshLoginForm() {
      this.$refs.loginForm.clearValidate("password", "code")
      this.loginForm.password = '';
      this.loginForm.code = '';
    },
    toRegister() {
      this.$router.push("/Register")
    },
  }
}
</script>

<style lang="less" scoped>

.login_container {
  background-color: #2b4b6b;
  height: 100%;
}

.login_x {
  background-color: #b2bbbe;
  width: 27%;
  height: 370px;
  border-radius: 9px;
  position: absolute;
  left: 50.4%;
  top: 46%;
  transform: translate(-50%, -50%);
  filter:opacity(80%)
}

.inner_box {
  margin-top: 30px;
  margin-left: 11%;
  width: 80%;
  height: 450px;
}

.title {
  color: #000000;
  text-align: center;
}

a {
  color: #000000;
  margin: 20px;
  font-weight: bold;
}

.login_header {
  //padding-bottom: 10px;

  text-align: center;
  line-height: 50px;
}

.login_header span {

  margin-right: 20px;
  cursor: pointer;
}

.body_item {
  margin-top: 20px;
  border: 0px solid #999;
  overflow: hidden;
}

.active {
  color: #4e7ca1;
  padding-bottom: 10px;
  border-bottom: 3px solid #4e7ca1;
}

</style>